package com.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.barriers.DistributedBarrier;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * Author Name: Justice
 * Project Name: zookeepercurator
 * File Name: Barrier2
 * Package Name: com.curator
 * Date: 2020-02-22 23:02
 * Copyright (c) 2020,All Rights Reserved.
 * 模拟田径比赛各位选手, 起跑最后达到终点
 */


public class Barrier2 {
    private static DistributedBarrier barrier = null;

    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 10; i++) {
            new Thread("线程" + i) {
                @Override
                public void run() {
                    try {
                        // 超时后等1秒再重试, 最多重试5次
                        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 5);
                        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
                                .connectString(AddressUtil.ADDRESS)
                                .connectionTimeoutMs(10000).sessionTimeoutMs(10000)
                                .retryPolicy(retryPolicy)
                                .build();
                        // 开启连接
                        curatorFramework.start();
                        barrier = new DistributedBarrier(curatorFramework, "/barrier2");
                        System.err.println(Thread.currentThread().getName() + "栅栏");
                        // 各就各位
                        barrier.setBarrier();
                        // 等号令员开枪
                        barrier.waitOnBarrier();
                        System.err.println("开始执行了");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
        Thread.sleep(8000);
        // 开枪
        if (barrier != null) {
            barrier.removeBarrier();
        }
        Thread.sleep(8000);
    }
}
